package com.wzq.upms.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wzq.permission.client.model.admin.UserModel;
import com.wzq.permission.client.service.UserService;
import com.wzq.upms.annotation.Auth;
import com.wzq.upms.common.utils.MD5Utils;
import com.wzq.upms.core.JsonResponse;
import com.wzq.upms.core.SessionUtils;

@Controller
public class IndexController {	
	@Autowired
	private UserService userServiceClient;
	/**
	 * 首页
	 * @param request
	 * @return
	 */
	@RequestMapping("/")
	@Auth(verifyURL=false)
	public String index(HttpServletRequest request){
		UserModel userModel =SessionUtils.getUser(request);
		if(userModel != null){
			return "index";
		}else{
			return "loginPage";
		}
	}
	
	/**
	 * 修改密码
	 * @param oldPassword 老密码
	 * @param newPassword 新密码
	 * @return
	 * @throws Exception 
	 */
	@Auth(verifyURL=false)
	@RequestMapping("/modifyPwd")
	@ResponseBody
	public JsonResponse modifyPwd(String oldPassword,String newPassword,HttpServletRequest request) throws Exception{
		UserModel sessionUser = SessionUtils.getUser(request);
		JsonResponse response = new JsonResponse();
		if(sessionUser == null){
			response.setMsg("对不起,登录超时.");
			response.setResult(JsonResponse.FAIL);
			return response;
		}
		UserModel userModel  = userServiceClient.queryById(sessionUser.getUserId());
		if(userModel == null || "1".equals(userModel.getDeleted())){
			response.setMsg("对不起,用户不存在.");
			response.setResult(JsonResponse.FAIL);
			return response;
		}
		//匹配旧密码
		if(!MD5Utils.verifyPwd(oldPassword, userModel.getPassword())){
			response.setMsg("旧密码输入不匹配.");
			response.setResult(JsonResponse.FAIL);
			return response;
		}
		userModel.setPassword(MD5Utils.encodePwd(newPassword));
		userServiceClient.updateBySelective(userModel);
		response.setMsg("修改密码成功.");
		response.setResult(JsonResponse.SUCCESS);
		return response;
	}
	
	/**
	 * 403页面
	 * @param request
	 * @return
	 */
	@RequestMapping("/error/403")
	@Auth(verifyURL=false)
	public String error403(HttpServletRequest request){
		return "error/403";
	}
	
	/**
	 * 404页面
	 * @param request
	 * @return
	 */
	@RequestMapping("/error/404")
	@Auth(verifyURL=false)
	public String error404(HttpServletRequest request){
		return "error/404";
	}
	
	/**
	 * 500页面
	 * @param request
	 * @return
	 */
	@RequestMapping("/error/500")
	@Auth(verifyURL=false)
	public String error500(HttpServletRequest request){
		return "error/500";
	}
}
